package com.lm.bytebuddy.example;

import com.lm.bytebuddy.ele.ExistingClass;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.agent.builder.ResettableClassFileTransformer;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.utility.JavaModule;

import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;

import static net.bytebuddy.matcher.ElementMatchers.named;

public class ModifyClassExample {
    public static void main(String[] args) {
        Instrumentation install = ByteBuddyAgent.install();// 安装 ByteBuddy 的代理

        ResettableClassFileTransformer sayHello = new AgentBuilder.Default()
                .type(named("com.lm.bytebuddy.ele.ExistingClass")) // 匹配目标类
                .transform(new AgentBuilder.Transformer() {
                               @Override
                               public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader, JavaModule javaModule, ProtectionDomain protectionDomain) {
                                   return builder.method(named("sayHello")) // 匹配目标方法
                                           .intercept(Advice.to(SayHelloAdvice.class));
                               }
                           } // 添加切面逻辑
                ).installOnByteBuddyAgent();

        // 调用修改后的方法
        ExistingClass existingClass = new ExistingClass();
        existingClass.sayHello(); // 输出：Modified: Hello, World!
    }

    public static class SayHelloAdvice {
        @Advice.OnMethodEnter
        public static void onEnter() {
            System.out.println("Modified: Hello, World!");
        }
    }
}